package com.example.daibanshiwu.Service.Impl;

import com.example.daibanshiwu.Service.MatterService;
import com.example.daibanshiwu.mapper.MatterMapper;
import com.example.daibanshiwu.pojo.FileDTO;
import com.example.daibanshiwu.pojo.Message;
import com.example.daibanshiwu.pojo.MessageDetailDTO;
import com.example.daibanshiwu.pojo.ProcessingRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class MatterServiceImpl implements MatterService {
    @Autowired
    private MatterMapper matterMapper;

    @Override
    public List<Message> getMessage(int receiverUserId){
        List<Message> listM=matterMapper.getMessage(receiverUserId);
        return listM;
    }

    @Override
    public void UpdateStatus(Integer messageId,String status) {
        matterMapper.updateStatus(messageId,status);
    }

    //插入新的处理记录
    @Override
    public ProcessingRecord createRecord(ProcessingRecord record, MultipartFile attachmentFile) throws IOException {
        // 1. 处理可选的附件
        if (attachmentFile != null && !attachmentFile.isEmpty()) {
            // 从 MultipartFile 中获取字节数组
            byte[] fileBytes = attachmentFile.getBytes();

            // 将文件信息设置到record对象中
            record.setAttachmentContent(fileBytes); // 设置文件内容
            record.setAttachmentFilename(attachmentFile.getOriginalFilename()); // 设置原始文件名
            record.setAttachmentContentType(attachmentFile.getContentType()); // 设置MIME类型
        }
        record.setProcessTime(LocalDateTime.now());
        matterMapper.insertProcessingRecord(record);
        record.setAttachmentContent(null); // 清理掉内容，只返回元数据
        return record;
    }

    //查询详情
    @Override
    public MessageDetailDTO getMessageDetailById(Integer messageId) {
        return matterMapper.findDetailById(messageId);
    }

    //预览文件
    @Override
    public FileDTO getFileByMessageId(String messageId) {
        FileDTO fileDTO = matterMapper.findFileByMessageId(messageId);

        // 如果数据库没有存 contentType，这里获取
        if (fileDTO != null && fileDTO.getContentType() == null) {
            // 使用 Spring 的工具类根据文件名猜测 MIME 类型
            String contentType = MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE; // 默认是二进制流
            try {
                Path path = new File(fileDTO.getFileName()).toPath();
                contentType = Files.probeContentType(path);
            } catch (IOException e) {
                // 忽略异常，使用默认值
                System.err.println("无法检测文件类型: " + e.getMessage());
            }
            fileDTO.setContentType(contentType);
        }

        return fileDTO;
    }
}
